package cn.com.elite;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.sql.Types; 
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class EliteDBLink implements Runnable{
	private static final Log log=LogFactory.getLog(EliteDBLink.class);
	private static int Hz=30; 
	public static cn.com.elite.EliteBean1 ebeana;
	public static cn.com.elite.EliteBean2 ebeanb;
	public static String address;
	public static String time;
	public static String CYCLE;
	public static boolean auto;
	private boolean flag = true; //停止线程标记 
	private static String daytime="";
	
	
	public static String getCYCLE() {
		return CYCLE;
	}
	public static void setCYCLE(String cycle) {
		CYCLE = cycle;
	}
	public static String getTime() {
		return time;
	}
	public static void setTime(String time) {
		EliteDBLink.time = time;
	}
	public cn.com.elite.EliteBean1 getEbeana() {
		return ebeana;
	}
	public void setEbeana(cn.com.elite.EliteBean1 ebeana) {
		this.ebeana = ebeana;
	}
	public cn.com.elite.EliteBean2 getEbeanb() {
		return ebeanb;
	}
	public void setEbeanb(cn.com.elite.EliteBean2 ebeanb) {
		this.ebeanb = ebeanb;
	}
	public static String getAddress() {
		return address;
	}
	public static void setAddress(String address) {
		EliteDBLink.address = address;
	}
	public static boolean isAuto() {
		return auto;
	}
	public static void setAuto(boolean auto) {
		EliteDBLink.auto = auto;
	}
	public static void main(String[] args){
		Date date=new Date();
		String ee=String.format("%tR",date); //获取现在几点
		String dd=String.format("%tF",date); //获取现在几号
		String now1=ee.substring(0,2);
		System.out.println("ee:"+ee);
		System.out.println("dd:"+dd);
		System.out.println("now1:"+now1);
	}
	public void run(){	
		Properties pros=readFile();
		if(pros!=null){
			Hz=Integer.parseInt(pros.getProperty("HZ"));
		}		
		while(flag){
			Date date=new Date();
			String ee=String.format("%tR",date); //获取现在几点
			String dd=String.format("%tF",date); //获取现在几号
			String now1=ee.substring(0,2);
			log.info("dd:"+dd);
			log.info("daytime:"+daytime);
			log.info("now1:"+now1);
			log.info("CYCLE:"+CYCLE);
			log.info("time:"+time);
			int judge=0;
			if(CYCLE.equals("1")){
				if(now1.equals(time)&&!dd.equals(daytime)){
					judge=1;
				}
			}else if(CYCLE.equals("2")){
				judge=1;
			}
			log.info("judge:"+judge);
			if(judge==1){
				log.info("------------------StartRun()----------------------");
				StartRun();
				daytime=dd;
				log.info("-------------------------同步完成--------------------------");
			}else{
				log.info("------------------条件未到不同步,进程休眠"+Hz*1000+"秒----------------------");
			}
            try{
            	Thread.sleep(Hz*1000);
            }catch(Exception e){
            	log.error("定时错误:"+EliteUtil.getERRO(e)); 
            }
		}		
	}
	public void StartRun(){
		log.info("---------------------------EliteDBLink start------------------------------------------");
		try{
			Properties pros=readFile();
			if(pros!=null){
				int count=Integer.parseInt(pros.getProperty("COUNT"));
				log.info("count:"+count);
				for(int i=1;i<count+1;i++){
//					if(i==8){
//						int aaa=ebeanb.deltetsql(" delete from staff ");
//						log.info("aaa:"+aaa); 
//					}  
					String q_sql=pros.getProperty("QuerySql"+i);
					log.info("q_sql:"+q_sql);
					List result=ebeana.chaxun(q_sql);
					if(result!=null&&result.size()>0){
						String InsertSql=pros.getProperty("InsertSql"+i);
						log.debug("InsertSql:"+InsertSql);
						String InsertSqlType=pros.getProperty("InsertSqlType"+i);
						log.debug("InsertSqlType:"+InsertSqlType);
						
						String DeleteSql_flag=pros.getProperty("DeleteSql_flag"+i);
						log.debug("DeleteSql_flag:"+DeleteSql_flag);
						String DeleteSql=pros.getProperty("DeleteSql"+i);
						log.debug("DeleteSql:"+DeleteSql);
						String DeleteSqlType=pros.getProperty("DeleteSqlType"+i);
						log.debug("DeleteSqlType:"+DeleteSqlType);
						String DeleteContent=pros.getProperty("DeleteContent"+i);
						log.debug("DeleteContent:"+DeleteContent);
						Object[] ContentParam1=getContent(DeleteContent,result);
						int[] types1=getType(DeleteSqlType);
						
						int[] types=getType(InsertSqlType);
						String InsertContent=pros.getProperty("InsertContent"+i);
						log.debug("InsertContent:"+InsertContent);
						Object[] ContentParam=getContent(InsertContent,result);
						String UpdateSql=pros.getProperty("UpdateSql"+i);
						String flag1=pros.getProperty("UpdateSql_flag"+i);
						log.debug("UpdateSql:"+UpdateSql);
						log.debug("flag1:"+flag1);
						if(ContentParam!=null&&ContentParam.length>0){
							for(int n=0;n<ContentParam.length;n++){
								String insertresult=ebeanb.insertPersonUseExecute(InsertSql,types,(Object[])ContentParam[n],UpdateSql,flag1,DeleteSql,types1,(Object[])ContentParam1[n],DeleteSql_flag);
								log.debug("insertresult:"+insertresult);
                                if(!insertresult.equals("0")){
                                	log.debug("insertresult_sql:"+insertresult);
                                	int result1=ebeana.update(insertresult);
                                	log.debug("insertresult_result1:"+result1);
                                }
							}
						}
						
					}else{
						log.info("result.size():"+result.size());
					}
				}
			}else{
				log.info("读取配置文件失败");  
			}
//			ebeanb.doProcess();
//			ebeanb.update("insert into mailservice(Updatetime,workflag,mailflag,cityflag)Values(GETDATE(),1,0,'BJ')");
		}catch(Exception e){ 
			log.error("过程出错:"+EliteUtil.getERRO(e));  
		}
	}
	
	private Object[] getContent(String InsertContent,List result){
		if(InsertContent!=null&&!InsertContent.equals("")&&InsertContent.length()>0){
			try{
				String[] content=InsertContent.split(",");
				if(content!=null&&content.length>0){
					Object[] ContentParam=new Object[result.size()];
					for(int n=0;n<result.size();n++){
						Object[] params=new Object[content.length];
						Map map=(Map)result.get(n);
						for(int m=0;m<content.length;m++){
							log.debug("content[m]:"+content[m]);
							params[m]=map.get(content[m]);
							log.debug("params[m]:"+params[m]);
						}
						ContentParam[n]=params;
					}
					return ContentParam;
				}
			}catch(Exception e){
				log.info("获得内容失败:"+EliteUtil.getERRO(e));  
			}
		}else{
			log.info("获得内容失败");  
		}
		return null;
	}
	private int[] getType(String InsertSqlType){
		if(InsertSqlType!=null&&!InsertSqlType.equals("")&&InsertSqlType.length()>0){
			try{
				String[] sqltype=InsertSqlType.split(",");
				if(sqltype!=null&&sqltype.length>0){
					int[] types=new int[sqltype.length];
					for(int i=0;i<sqltype.length;i++){
						if(sqltype[i].equals("CHAR")){
							types[i]=Types.VARCHAR;
						}else if(sqltype[i].equals("INT")){
							types[i]=Types.INTEGER;
						}else if(sqltype[i].equals("DATE")||sqltype[i].equals("TIMESTAMP")){
							types[i]=Types.TIMESTAMP;
						}else if(sqltype[i].equals("DECIMAL")){
							types[i]=Types.DECIMAL;
						}else{
							log.info("获得参数类型失败");  
							return null;
						}
					}
					return types;
				}
			}catch(Exception e){
				log.info("获得参数类型失败:"+EliteUtil.getERRO(e));  
			}			
		}else{
			log.info("获得参数类型失败");  
		}
		return null;
	}
	public static Properties readFile(){
		String fileName=address;
		InputStream in=null;  
        Properties pros=new Properties();  
        try{
        	if(null!=fileName){ 
        		in=new BufferedInputStream(new FileInputStream(fileName));
        		pros.load(in);
        		return pros;
        	}
        }catch(Exception e){
        	log.error("读取资源文件出错:"+EliteUtil.getERRO(e));  
        }finally{
        	try{
        		if(null!=in){
        			in.close(); 
        		}
        	}catch(Exception e){
        		log.error("关闭流失败:"+EliteUtil.getERRO(e));  
        	}
        	return pros;
        }
	}
}
